const Messages = require("../model/messageModel")

module.exports.addMessage = async (req, res, next) => {
  try {
    const { from, to, message } = req.body
    const data = await Messages.create({
      text: message,
      users: [from, to],
      sender: from,
    })
    if (data) {
      return res.json({ status: true, msg: "Message added successfully." })
    } else {
      return res.json({
        status: false,
        msg: "Failed to add message to the database.",
      })
    }
  } catch (ex) {
    next(ex)
  }
}

module.exports.getAllMessage = async (req, res, next) => {
  try {
    const { from, to } = req.body

    const messages = await Messages.find({
      users: {
        // $in 返回存在数组中检索字段的记录
        // $all 返回满足数组中所有检索字段的记录
        $all: [from, to],
      },
    }).sort({ updatedAt: 1 })

    const projectMessages = await messages.map((message) => {
      return {
        fromSelf: message.sender.toString() === from,
        message: message.text,
      }
    })

    return res.json({ status: true, projectMessages })
  } catch (ex) {
    next(ex)
  }
}
